package com.shanghaionstar.smart;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.TextView;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.smart.SmartDevicesResponse;
import com.onstar.cn.weight.ProgressLayout;
import com.onstar.cn.weight.ToastView;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.smart.adapter.DeviceExListAdapter;
import com.shanghaionstar.smart.iview.ISmartListView;
import com.shanghaionstar.smart.presenter.SmartDeviceListPresenter;
import com.shanghaionstar.smart.swipemenulistview.SwipeMenu;
import com.shanghaionstar.smart.swipemenulistview.SwipeMenuExpandableCreator;
import com.shanghaionstar.smart.swipemenulistview.SwipeMenuExpandableListView;
import com.shanghaionstar.smart.swipemenulistview.SwipeMenuItem;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.BusinessUtil;

/**
 * Created by Rengui Lu on 2016/6/12.
 */
public class SmartDeviceListFrg extends BaseFragment implements View.OnClickListener, ISmartListView {
    private static final String TAG = SmartDeviceListFrg.class.getSimpleName();
    @FindViewById(R.id.device_lv)
    SwipeMenuExpandableListView mDeviceLv;
    @FindViewById(R.id.sub_title_tv)
    TextView mSubTv;
    @FindViewById(R.id.configure_pl)
    ProgressLayout mConfigurePl;

    private BaseActivity mActivity;
    private DeviceExListAdapter mAdapter;
    private int sign = -1;

    private SmartDeviceListPresenter presenter;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = (BaseActivity) activity;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        presenter = new SmartDeviceListPresenter(mActivity.getScheduler());
        presenter.setView(this);
        if (isFirstLoad()) {
            initView();
            mDeviceLv.setGroupIndicator(null);
            mDeviceLv.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
                @Override
                public boolean onGroupClick(ExpandableListView expandableListView, View view, int groupPosition, long l) {
                    SmartDeviceListFrg.this.onGroupClick(groupPosition);
                    return true;
                }
            });
            mDeviceLv.setMenuCreator(creator);
            mDeviceLv.setOnMenuItemClickListener(new SwipeMenuExpandableListView.OnMenuItemClickListenerForExpandable() {
                @Override
                public boolean onMenuItemClick(int groupPostion, int childPostion, SwipeMenu menu, int index) {
                    presenter.onMenuItemClick(groupPostion);
                    return false;
                }
            });
        }
        presenter.getSmartDevices();
    }

    private void onGroupClick(int groupPosition) {
        try {
            if (sign == -1) {
                // 展开被选的group
                mConfigurePl.setVisibility(View.VISIBLE);
                mDeviceLv.expandGroup(groupPosition);
                mAdapter.curPos = groupPosition;
                presenter.groupClick(groupPosition);
                sign = groupPosition;
            } else if (sign == groupPosition) {
                mDeviceLv.collapseGroup(sign);
                sign = -1;
            } else {
                mDeviceLv.collapseGroup(sign);
                // 展开被选的group
                mConfigurePl.setVisibility(View.VISIBLE);
                mDeviceLv.expandGroup(groupPosition);
                mAdapter.curPos = groupPosition;
                presenter.groupClick(groupPosition);
                sign = groupPosition;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void createMenu(SwipeMenu menu) {
        SwipeMenuItem item1 = new SwipeMenuItem(OnstarApplication.getApplication());
        item1.setBackground(new ColorDrawable(Color.rgb(0xFA, 0x68, 0x68)));
        item1.setWidth(CommonUtil.dp2px(90, mActivity));
        item1.setHeight(CommonUtil.dp2px(105, mActivity));
        item1.setTitle(R.string.smart_del);
        item1.setTitleColor(Color.WHITE);
        item1.setTitleSize(16);
        menu.addMenuItem(item1);
    }


    SwipeMenuExpandableCreator creator = new SwipeMenuExpandableCreator() {
        @Override
        public void createGroup(SwipeMenu menu) {
            createMenu(menu);
        }

        @Override
        public void createChild(SwipeMenu menu) {
        }
    };


    private void showFailedDia() {
        new AlertDialog.Builder(mActivity)
                .setMessage(getString(R.string.smart_obtain_failed))
                .setPositiveButton(R.string.smart_try_again, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        presenter.getSmartDevices();
                    }
                })
                .setNegativeButton(R.string.smart_cancel, null)
                .show();
    }


    private void initView() {
        mSubTv.setText(R.string.smart_trigger_setting);
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_slk_add_device_list;
    }


    @OnClick({R.id.add_btn, R.id.sub_title_tv, R.id.back_ib, R.id.fun_intro_tv})
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.add_btn:
                presenter.addClick();
                break;
            case R.id.sub_title_tv:
                presenter.goToTrigger();
                break;
            case R.id.back_ib:
                BusinessUtil.sendReportByClickType(mActivity, FunctionNameFindId.Smarthome_applist_return.getStringValue());
                mActivity.finish();
                break;
            case R.id.fun_intro_tv:
                presenter.goToFunIntro();
                break;
        }
    }


    @Override
    public void initData(SmartDevicesResponse mSmartDevicesRes) {
        mAdapter = new DeviceExListAdapter(mActivity, mSmartDevicesRes, mConfigurePl);
        mDeviceLv.setAdapter(mAdapter);
    }


    @Override
    public void setLoading(boolean isLoading) {
        mConfigurePl.setVisibility(isLoading ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onResponseError(OnStarException e) {
        showFailedDia();
    }

    @Override
    public void onReponseSuccess(Object object) {

    }

    @Override
    public Activity onActivity() {
        return mActivity;
    }


    @Override
    public void notifyDataChange() {
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onGetDetailError(Throwable e) {
        mDeviceLv.collapseGroup(sign);
        sign = -1;
        assert e != null;
        new ToastView(mActivity).showToast(e.getMessage() == null ? "" : e.getMessage());
    }

    @Override
    public void onMenuClickError(Throwable throwable) {
        if (throwable != null)
            AlertDialogUtil.showDialogByOnstarException(mActivity, (OnStarException) throwable);
    }
}
